package com.teach.controller;


import com.teach.config.RabbitmqConfig;
import com.teach.dto.IdDto;
import com.teach.entity.ResponseEntity;
import com.teach.service.SeckillService;
import com.teach.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/seckill")
@Api(tags = "秒杀的控制层")
public class SeckillController {
    @Resource
    SeckillService seckillService;
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    RabbitmqConfig rabbitMqConfig;
    @Resource
    RabbitTemplate rabbitTemplate;

    /*@Scheduled(cron = "0 0/5 21-22 * * ?")*/
    @Scheduled(fixedDelay = 10*1000)
    public void addRedis(){
        seckillService.addRedis();
    }

    @PostMapping("/seckillgoods")
    @ApiOperation("秒杀商品")
    public ResponseEntity seckillGoods(HttpServletRequest request, @RequestBody IdDto idDto){
        String token = request.getHeader("token");
        //获取iP地址
        /*String remoteAddr = request.getRemoteAddr();
        redisTemplate.opsForValue().increment(remoteAddr,1);
        Integer num = (Integer) redisTemplate.opsForValue().get(remoteAddr);
        if(num>3){
            redisTemplate.expire(remoteAddr,5, TimeUnit.SECONDS);
            return new ResponseEntity(null,500,"访问过于频繁",false);
        }*/
        return seckillService.seckillGoods(idDto,token);
    }

    /** * 发送端代码 * @param message 消息数据 * @param ttlesg  过期时间 * @return */
    @RequestMapping("sendMsg/{message}/{ttlesg}")
    public String sendMsg(@PathVariable String message, @PathVariable Integer ttlesg){
        System.out.println("发送端开始发送消息");
        rabbitTemplate.convertAndSend(RabbitmqConfig.DELAY_EXCHANGE,
                RabbitmqConfig.DELAY_MESSAGE_KEY,message,messg ->{
                messg.getMessageProperties().setDelay(ttlesg);
                return messg;
            });
        return "ok";
    }

}
